import { FC, useEffect, useState } from 'react';
import {
  Card,
  Space,
  Button,
  Form,
  Input,
  Select,
  Table,
  Popconfirm,
  Pagination,
  Modal,
  DatePicker,
  message,
} from 'antd';

import { studentsListApi, studentsDelApi, studentsAddApi } from '@/utils/api';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';

const fn = (text: number) => {
  const date = new Date(text);
  const y = date.getFullYear();
  const m = date.getMonth() + 1;
  const d = date.getDate();
  return y + '-' + m + '-' + d;
};

/*
  列表接口
  url: http://www.pudge.wang:3333/api/students/list
  method: get
  params: {
    page_size?: number  默认10
    current_page?: number  默认1
    name?: string 
    sex?: number
  }
*/

interface StudentType {
  birthday: number;
  city: string;
  name: string;
  sex: string;
  _id: string;
  [propname: string]: any;
}

const Index: FC = () => {
  const [form] = Form.useForm();
  const [searchObj, setSearchObj] = useState({});
  const search = () => {
    // console.log(form.getFieldsValue());
    setSearchObj(form.getFieldsValue());
    set_current_page(1);
  };
  const reset = () => {
    form.resetFields();
    setSearchObj({});
  };

  const [dataSource, setDataSource] = useState<StudentType[]>([]);
  const [total, setTotal] = useState<number>(0);
  // 每页条数
  const [page_size, set_page_size] = useState<number>(10);
  const [current_page, set_current_page] = useState<number>(1);
  const [rerender, forceUpdate] = useState({});
  useEffect(() => {
    (async () => {
      const res = await studentsListApi({
        page_size: page_size,
        current_page: current_page,
        ...searchObj,
      });
      const result = res.result.map((item: StudentType) => {
        return { ...item, key: item._id };
      });
      setDataSource(result);
      setTotal(res.count);
    })();
  }, [current_page, page_size, searchObj, rerender]);

  const change = (page: number, pageSize: number) => {
    set_current_page(page || 1);
    set_page_size(pageSize);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render(text: string) {
        return <span>{text === '1' ? '男' : '女'}</span>;
      },
    },
    {
      title: '籍贯',
      dataIndex: 'city',
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      render(text: number) {
        const date = new Date(text);
        const y = date.getFullYear();
        const m = date.getMonth() + 1;
        const d = date.getDate();
        return y + '-' + m + '-' + d;
      },
    },
    {
      title: '操作',
      width: 200,
      render(text: any, record: any) {
        return (
          <Space>
            <Button onClick={openEdit(record)}>编辑</Button>
            <Popconfirm
              title="Are you sure to delete this task?"
              onConfirm={confirm(record)}
              okText="Yes"
              cancelText="No"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const confirm = (record: any) => async () => {
    // console.log('ok');
    // console.log(record);
    const res = await studentsDelApi({ id: record._id });
    if (res) {
      forceUpdate({});
    }
  };

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增学员');
  const [form2] = Form.useForm();
  const showModal = () => {
    form2.resetFields();
    setModalTitle('新增学员');
    setIsModalVisible(true);
  };
  const handleOk = () => {
    // setIsModalVisible(false);
    // console.log(new Date(form2.getFieldsValue().birthday).getTime());
    // console.log({
    //   ...form2.getFieldsValue(),
    //   birthday: new Date(form2.getFieldsValue().birthday).getTime(),
    // });
    form2
      .validateFields()
      .then(async (res) => {
        if (modalTitle === '新增学员') {
          const response = await studentsAddApi({
            ...res,
            birthday: new Date(form2.getFieldsValue().birthday).getTime(),
          });
          if (response) {
            setIsModalVisible(false);
            message.success('新增成功');
            forceUpdate({});
          }
        } else if (modalTitle === '编辑学员') {
        }
      })
      .catch((err) => {
        return err;
      });
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const openEdit = (record: StudentType) => () => {
    console.log(record);
    form2.setFieldsValue({
      name: record.name,
      sex: record.sex,
      city: record.city,
      // birthday: record.birthday,
      birthday: moment(fn(record.birthday), 'YYYY/MM/DD'),
    });
    setModalTitle('编辑学员');
    setIsModalVisible(true);
  };

  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      <Card>
        <Form form={form} name="horizontal_login" layout="inline">
          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item name="sex" label="性别">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">男</Select.Option>
              <Select.Option value="2">女</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={search}>
                搜索
              </Button>
              <Button onClick={reset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          style={{ float: 'right', marginBottom: 20 }}
          onClick={showModal}
        >
          新增
        </Button>
        <Table
          dataSource={dataSource}
          columns={columns}
          pagination={false}
        ></Table>
        <Pagination
          showSizeChanger
          current={current_page}
          total={total}
          style={{ marginTop: 20, display: 'flex', justifyContent: 'flex-end' }}
          onChange={change}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form2}
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          autoComplete="off"
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: 'Please input your name!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="性别"
            name="sex"
            rules={[{ required: true, message: 'Please choose your sex!' }]}
          >
            <Select allowClear>
              <Select.Option value="1">男</Select.Option>
              <Select.Option value="2">女</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="城市"
            name="city"
            rules={[{ required: true, message: 'Please input your city!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="出生日期"
            name="birthday"
            rules={[
              { required: true, message: 'Please choose your birthday!' },
            ]}
          >
            <DatePicker />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
};

export default Index;
